<?php

namespace app\controller;

use think\Request;
use think\facade\Db;

class Client
{
	public function keyword(Request $request)
	{
		$deviceId = $request->header('deviceId');
		if (empty($deviceId)) {
			return json(['code' => 403, 'verify' => 0, 'keyword' => []]);
		}

		$arrarId = [];
		$arrarKeywords = [];
		$query = Db::table('cfg_xhs_keywords')->field('id, keywords')->where('status', 0)->order('priority', 'desc')->limit(10)->select()->toArray();
		if (is_array($query)) {
			foreach ($query as $value) {
				array_push($arrarId, $value['id']);
				array_push($arrarKeywords, $value['keywords']);
			}
		}

		if (count($arrarId) == 0) {
			return json(['code' => 403, 'verify' => 0, 'keyword' => []]);
		}

		$query = Db::table('cfg_xhs_device')->where('deviceId', $deviceId)->value('id');
		if(empty($query)) {
			Db::name('cfg_xhs_device')->insert(['status' => 1, 'create'=> time(), 'datetime'=> time(), 'deviceId' => $deviceId]);
		}

		$count = Db::table('cfg_xhs_keywords')->where('status', 0)->count();
		if(empty($count)) {
			Db::name('cfg_xhs_keywords')->update(['status' => 0]);
		}

		Db::name('cfg_xhs_keywords')->where('id', 'in', $arrarId)->update(['status' => 1, 'deviceId' => $deviceId]);

		$verify = md5(implode('', $arrarId));
		return json(['code' => 200, 'verify' => $verify, 'keyword' => $arrarKeywords]);
	}

	public function received(Request $request)
	{
		$deviceId = $request->header('deviceId');
		if (empty($deviceId)) {
			return json(['code' => 0]);
		}

		$datetime = $request->param('time', '', 'trim'); // 发布时间

		$keywords = $request->param('keywords', '', 'trim'); // 关键词

		$type = $request->param('type', '', 'trim'); //广告类型

		$title = $request->param('title', '', 'trim'); // 标题

		$company = $request->param('company', '', 'trim'); // 作者

		$locationTV = $request->param('locationTV', '', 'trim'); // 作者所在位置

		$comments = $request->param('comments', '', 'trim'); // 评论数

		$love = $request->param('love', '', 'trim'); // 爱心数

		$star = $request->param('star', '', 'trim'); // 点赞数

		$url = $request->param('url', '', 'trim'); // 链接

		$tag = $request->param('tag', '', 'trim'); // 标签

		if (empty($url)) {
			return json(['code' => 0]);
		}

		$chr = chr(239);
		$pos = strpos($url, $chr);
		if ($pos !== false) {
			$http = 'http://';
			$pos = strpos($url, $http);
			if ($pos !== false) {
				$prefix = strstr($url, $http);
				$address = $this->getRandAddress();
				$url = $this->getUrlParameter(substr($prefix, 0, strpos($prefix, $chr)), $address);
			}
		}

		if ($url === false) {
			return json(['code' => 0]);
		}

		if (empty($type)) {
			return json(['code' => 0]);
		}

		//1广告, 2赞助
		$typeValue = 1;
		if($type == '赞助') {
			$typeValue = 2;
		}

		if (empty($love)) {
			$love = 0;
		}

		if (empty($star)) {
			$star = 0;
		}

		if (empty($comments)) {
			$comments = 0;
		}

		$urlex = $url;
		$love = intval($love);
		$star = intval($star);
		$url = $this->urlParse($url);
		$comments = intval($comments);

		// 查询关键词所属行业
		$bazaarId = Db::table('cfg_xhs_keywords')->where('keywords', $keywords)->value('bazaarId');
		if( empty($bazaarId) ) {
			return json(['code' => 0]);
		}

		// 更新关键词状态
		Db::name('cfg_xhs_keywords')->where('keywords', $keywords)->update([
			'datetime' => time(),
			'status' => 2
		]);

		// 更新设备状态
		Db::name('cfg_xhs_device')->where('deviceId', $deviceId)->update(['status' => 1, 'datetime' => time() ]);

		// 写入URL访问记录
		$id = Db::table('cfg_xhs_url')->where('url', $url)->value('id');
		if (empty($id)) {
			$showpos = Db::table('cfg_xhs_url')->where('keywords', $keywords)->count();
			if(empty($showpos)) {
				$showpos = 0;
			}
			$showpos = bcadd($showpos, 1);
			Db::name('cfg_xhs_url')->insert(
				[
					'bazaarId' => $bazaarId, 'type' => $typeValue, 'title' => $title, 'company' => $company, 'keywords' => $keywords, 'showpos' => $showpos,
					'locationTV' => $locationTV, 'comments' => $comments, 'love' => $love, 'star' => $star, 'url' => $url, 'lasttime' => time(),
					'urlex' => $urlex, 'time' => time(), 'deviceId' => $deviceId, 'datetime' => $datetime, 'tag' => $tag
				]
			);
		} else {
			Db::name('cfg_xhs_url')->where('id', $id)->data(['bazaarId' => $bazaarId, 'lasttime' => time(), 'datetime' => $datetime, 'tag' => $tag, 'comments' => $comments, 'love' => $love, 'star' => $star])->inc('number', 1)->update();
		}

		// 写入关键词统计
    $advertisingNumber = Db::table('cfg_xhs_url')->where('type', 1)->where('keywords', $keywords)->whereDay('lasttime')->count();
    $sponsorNumber     = Db::table('cfg_xhs_url')->where('type', 2)->where('keywords', $keywords)->whereDay('lasttime')->count();
    $urlNumber         = Db::table('cfg_xhs_url')->whereDay('lasttime')->where('keywords', $keywords)->group('url')->count();
    $countNumber       = bcadd($advertisingNumber, $sponsorNumber);
		$id = Db::table('cfg_xhs_keywords_count')->where('keywords', $keywords)->whereDay('datetime')->value('id');
		if (empty($id)) {
			Db::name('cfg_xhs_keywords_count')->insert(
				[
					'bazaarId' => $bazaarId, 'keywords' => $keywords, 'advertisingNumber' => $advertisingNumber, 'sponsorNumber' => $sponsorNumber, 'urlNumber' => $urlNumber, 'countNumber' => $countNumber, 'datetime' => time()
				]
			);
		} else {
				Db::name('cfg_xhs_keywords_count')->where('id', $id)->update([ 'advertisingNumber' => $advertisingNumber, 'sponsorNumber' => $sponsorNumber, 'urlNumber' => $urlNumber, 'countNumber' => $countNumber ]);
		}

		// 写入公司统计
    $advertisingNumber = Db::table('cfg_xhs_url')->where('type', 1)->where('company', $company)->whereDay('lasttime')->count();
    $sponsorNumber     = Db::table('cfg_xhs_url')->where('type', 2)->where('company', $company)->whereDay('lasttime')->count();
    $urlNumber         = Db::table('cfg_xhs_url')->whereDay('lasttime')->where('company', $company)->group('url')->count();
    $countNumber       = bcadd($advertisingNumber, $sponsorNumber);
		$id = Db::table('cfg_xhs_company_count')->where('company', $company)->whereDay('datetime')->value('id');
		if (empty($id)) {
			Db::name('cfg_xhs_company_count')->insert(
				[
					'bazaarId' => $bazaarId, 'company' => $company, 'advertisingNumber' => $advertisingNumber, 'sponsorNumber' => $sponsorNumber, 'urlNumber' => $urlNumber, 'countNumber' => $countNumber, 'datetime' => time()
				]
			);
		} else {
				Db::name('cfg_xhs_company_count')->where('id', $id)->update([ 'advertisingNumber' => $advertisingNumber, 'sponsorNumber' => $sponsorNumber, 'urlNumber' => $urlNumber, 'countNumber' => $countNumber ]);
		}

		return json(['code' => 0]);
	}

	private function urlParse($url)
	{
		$chr = chr(63);
		$pos = strpos($url, $chr);
		if ($pos === false) {
			return $url;
		}
		$array = explode($chr, $url);
		if (count($array) > 1) {
			return $array[0];
		}
		return $url;
	}

	private function getRandAddress() {
		$ip_long = [
			['607649792', '608174079'], //36.56.0.0-36.63.255.255
			['1038614528', '1039007743'], //61.232.0.0-61.237.255.255
			['1783627776', '1784676351'], //106.80.0.0-106.95.255.255
			['2035023872', '2035154943'], //121.76.0.0-121.77.255.255
			['2078801920', '2079064063'], //123.232.0.0-123.235.255.255
			['-1950089216', '-1948778497'], //139.196.0.0-139.215.255.255
			['-1425539072', '-1425014785'], //171.8.0.0-171.15.255.255
			['-1236271104', '-1235419137'], //182.80.0.0-182.92.255.255
			['-770113536', '-768606209'], //210.25.0.0-210.47.255.255
			['-569376768', '-564133889'], //222.16.0.0-222.95.255.255
		];
		$rand_key = mt_rand(0, 9);
		return long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
	}

	private function getUrlParameter($url, $ip)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, [
			'CLIENT-IP: '.$ip,
			'X-FORWARDED-FOR: '.$ip,
			'user-agent: Mozilla/5.0 (Windows NT '. mt_rand(8, 10) .'.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/'. mt_rand(10, 90) .'.0.4240.'. mt_rand(10, 90) .' Safari/'.mt_rand(100, 700).'.36',
		]);
		for ($i = 0; $i < 5; $i++) {
			$exec = curl_exec($ch);
			$httpUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
			if ($httpUrl) {
				curl_close($ch);
				return $httpUrl;
			}
		}
		curl_close($ch);
		return false;
	}

	public function upgrade(Request $request)
	{
		return json(['version' => '1.0', 'url' => "https://xhs.jiafen520.com/shenyou.apk"]);
	}

}
